package com.yonyou.le.unattended.web;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.yonyou.iuap.mvc.type.JsonResponse;
import com.yonyou.le.unattended.cache.DeviceCacheManager;
import com.yonyou.le.unattended.cache.MonitorCacheManager;
import com.yonyou.le.unattended.cache.MonitorCacheTypeEnum;
import com.yonyou.le.unattended.cache.entity.DeviceData;
import com.yonyou.le.unattended.delivery.entity.DeviceParamVO;
import com.yonyou.le.unattended.delivery.enumeration.DevicePositionEnum;
import com.yonyou.le.unattended.delivery.enumeration.DevtypeEnum;
import com.yonyou.le.unattended.entity.meta.CarInfoData;
import com.yonyou.le.unattended.entity.meta.OperatDetail;
import com.yonyou.le.unattended.entity.meta.OperationPoint;
import com.yonyou.le.unattended.exception.NoGateTargetAdaptorException;
import com.yonyou.le.unattended.exception.NoTargetDeviceException;
import com.yonyou.le.unattended.service.OperationMonitorService;
import com.yonyou.le.unattended.service.PollService;
import com.yonyou.le.unattended.service.WsMessageService;
import com.yonyou.le.unattended.util.CommonUtils;
import com.yonyou.le.unattended.util.FindDevice;
/**
 * 作业点操作服务入口
 * @author weijw
 *
 */
@RestController
@RequestMapping(value="/monitor")
public class OperationMonitorController extends BaseController {
	private Logger logger = LoggerFactory.getLogger(OperationMonitorController.class);
	
	@Autowired
	private OperationMonitorService opservice;
	@Autowired
	private PollService pollService;
	@Autowired
	private DeviceCacheManager deviceCacheManager;
	@Autowired
	private MonitorCacheManager monitorCacheManager;
	@Autowired
	private WsMessageService wsMessageService;
	private final String OK="true";
	private final String ERROR="false";
	private final String RTSP_NONE="RTSP_NONE";
	private final String OPCODE="opcode";
    /**
     * 查詢作業點列表
     * 
     * @return
     */
    @RequestMapping(value = "/oplist", method = RequestMethod.GET)
    public Object opList(HttpServletRequest request) {
        logger.info("查询作業點列表");
        List<OperationPoint> ops = opservice.findAll();
        //List<OperationPoint> ops = opservice.findByUser();
        CommonUtils.sortListByAttr(OPCODE, ops);
        return super.buildSuccess(ops);
    }
    
    /**
     * 作业点详细信息
     * @param request
     * @return
     */
    @RequestMapping(value = "/monitorDetail")
    public Object monitorData(HttpServletRequest request){
    	String opCode = request.getParameter("opcode");
    	logger.info("作业点信息查询");
    	CarInfoData  data = opservice.selectMonitorData(opCode);
    	String video_before_code = deviceCacheManager.getMonitorDevice(opCode, FindDevice.getDevicePositonAndType(DevicePositionEnum.WEIGH_FRONT, DevtypeEnum.FVideoEnum), String.class);
    	String video_after_code = deviceCacheManager.getMonitorDevice(opCode, FindDevice.getDevicePositonAndType(DevicePositionEnum.WEIGH_AFTER, DevtypeEnum.FVideoEnum), String.class);
    	DeviceData video_before = null;
		if(StringUtils.isNotBlank(video_before_code)){
    		video_before = deviceCacheManager.getDeviceData(video_before_code, DeviceData.class);
    	}
    	DeviceData video_after = null;
		if(StringUtils.isNotBlank(video_after_code)){
    		video_after = deviceCacheManager.getDeviceData(video_after_code, DeviceData.class);
    	}
		List<String>  rtspList = new ArrayList<String>();
		if(video_before!=null){
			rtspList.add(video_before.getDeviceParamVO().getHcrtsp());
    	}else{
    		rtspList.add(RTSP_NONE);
    	}
    	if(video_after!=null){
    		rtspList.add(video_after.getDeviceParamVO().getHcrtsp());
    	}else{
    		rtspList.add(RTSP_NONE);
    	}
     	OperatDetail operatDetail = new OperatDetail(data,rtspList);
    	return super.buildSuccess(operatDetail);
    }
    /**
     * 抬杆
     * @param request
     * @return
     */
    @RequestMapping(value = "/pollUp", method = RequestMethod.GET)
    public Object pollUp(HttpServletRequest request){
    	String opcode = request.getParameter("opcode");
    	String position = request.getParameter("position");
    	logger.info("抬杆:作业点"+opcode+"位置："+position);
    	//找到对应设备
    	String pos_type=FindDevice.getDevicePositonAndType(position, DevtypeEnum.FDOEnum);
    	String deviceCode=deviceCacheManager.getMonitorDevice(opcode,pos_type, String.class);

    	boolean result = false;
		try {
			result = pollService.pollUp(deviceCode);
		} catch (NoGateTargetAdaptorException e) {
			logger.error(e.getMessage());
			e.printStackTrace();
			//通知监控
    		wsMessageService.sendMsg(opcode,CommonUtils.formatDate(new Date())+e.getMessage());
			JsonResponse buildSuccess = super.buildSuccess(e.getMessage());
	    	buildSuccess.setMessage(ERROR);
	    	buildSuccess.setSuccess(OK);				
		} catch (NoTargetDeviceException e) {
			logger.error(e.getMessage());
			e.printStackTrace();
			//通知监控
    		wsMessageService.sendMsg(opcode,CommonUtils.formatDate(new Date())+e.getMessage());
			JsonResponse buildSuccess = super.buildSuccess(e.getMessage());
	    	buildSuccess.setMessage(ERROR);
	    	buildSuccess.setSuccess(OK);			
		}
    	
    	if(result){
    		//通知监控
    		wsMessageService.sendMsg(opcode,CommonUtils.formatDate(new Date())+"手动抬杆"+deviceCode+"成功");
        	//通知监控车辆状态
    		Integer status = monitorCacheManager.getCacheData(MonitorCacheTypeEnum.PICTURE_STATUS, opcode, Integer.class);
    		if(status == null){//没有缓存的状态为0
    			status = 0 + 1;
    		}else if(status == 2){
    			status = 2 + 1;
    		}
    		monitorCacheManager.updatePictureStatus(opcode, status);
    		wsMessageService.changeState(opcode,status);
        	JsonResponse buildSuccess = super.buildSuccess("Poll up success");
        	buildSuccess.setMessage(OK);
    		return buildSuccess;
    	}else{
    		wsMessageService.sendMsg(opcode,"抬杆"+deviceCode+"失败，请求超时");
    		JsonResponse buildSuccess = super.buildSuccess("Failed in poll up, connect time out");
        	buildSuccess.setMessage(ERROR);
    		return buildSuccess;
    	}
    }
    
}
